package com.lld.im.service.callback;


import com.lld.im.common.ResponseVO;
import com.lld.im.common.config.AppConfig;
import com.lld.im.common.utils.HttpRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 服务回调 事件执行后 服务回调 通知各其它层
 */
@Service
@Slf4j
public class CallBackServer {


    @Autowired
    private AppConfig appConfig;

    @Autowired
    private HttpRequestUtils httpRequestUtils;

    /**
     * 服务回调 将数据通过httpClient转发给其他服务
     */
    public void callBack(Integer appId, String callBackCommand, String jsonBody) {
        Map<String, Object> headers = getHeaders(appId, callBackCommand);
        try {
            httpRequestUtils.doPost(appConfig.getCallbackUrl(), Object.class,
                    headers, jsonBody, null);
        } catch (Exception e) {
            log.error("回调发生异常:{}", e.getMessage());
        }
    }

    private Map<String, Object> getHeaders(Integer appId, String callBackCommand) {
        Map<String, Object> headers = new HashMap<>();
        headers.put("appId", appId);
        headers.put("callBackCommand", callBackCommand);
        return headers;
    }

    /**
     * 服务回调之前调用
     *
     * @param appId
     * @param callBackCommand
     * @param jsonBody
     */
    public ResponseVO beforeCallBack(Integer appId, String callBackCommand, String jsonBody) {
        try {
            ResponseVO responseVO = httpRequestUtils.doPost(appConfig.getCallbackUrl(), ResponseVO.class
                    , getHeaders(appId, callBackCommand), jsonBody, null);
            return responseVO;
        } catch (Exception e) {
            log.error("回调发生异常:{}", e.getMessage());
            return ResponseVO.successResponse();
        }
    }
}
